package com.weixing.mall.provider.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.weixing.mall.base.constant.GlobalConstant;
import com.weixing.mall.base.exception.BusinessException;
import com.weixing.mall.base.wrapper.Result;
import com.weixing.mall.core.support.auth.SysAuth;
import com.weixing.mall.provider.api.model.vo.ActivityProductVo;
import com.weixing.mall.provider.api.model.vo.ItemVo;
import com.weixing.mall.provider.api.model.vo.ProductStockVo;
import com.weixing.mall.provider.api.service.ItemFeign;
import com.weixing.mall.provider.mapper.ProductStockDetailsMapper;
import com.weixing.mall.provider.mapper.ProductStockMapper;
import com.weixing.mall.provider.mapper.StockCheckProductMapper;
import com.weixing.mall.provider.mapper.StockCheckProductPersonMapper;
import com.weixing.mall.provider.model.domain.*;
import com.weixing.mall.provider.model.dto.StockCheckGoodsDto;
import com.weixing.mall.provider.service.IDefectiveProductService;
import com.weixing.mall.provider.service.IDepotService;
import com.weixing.mall.provider.service.IStockCheckProductService;
import com.weixing.mall.util.ListUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 仓库模块-盘点单关联商品 服务实现类
 * </p>
 *
 * @author Small
 * @since 2019-11-15
 */
@Service
public class StockCheckProductServiceImpl extends ServiceImpl<StockCheckProductMapper, StockCheckProduct> implements IStockCheckProductService {

    @Autowired
    private ItemFeign productFeign;
    @Autowired
    private ProductStockMapper productStockMapper;
    @Autowired
    private StockCheckProductPersonMapper stockCheckProductPersonMapper;
    @Autowired
    private ItemFeign itemFeign;
    @Autowired
    private ProductStockDetailsMapper stockDetailsMapper;
    @Autowired
    private IDepotService depotService;
    @Autowired
    private IDefectiveProductService defectiveProductService;
    @Override
    public void stockCheckGoods(StockCheckGoodsDto stockCheckGoodsDto, Long uid) {

        //盘点单id
        Long checkId = stockCheckGoodsDto.getCheckId();
        //货号
        String productSn = stockCheckGoodsDto.getProductSn();
        StockCheckProduct stockCheckProduct = baseMapper.selectStockCheckProduct(checkId, productSn);
        //通过盘点单号和货号没查到信息就新增
        if (stockCheckProduct == null) {
            //通过货号查询货品相关信息
            ItemVo productVo = productFeign.findProductVoByProductSn(productSn).getData();
            //商品货品名称
            String productName = productVo.getProductName();
            //货品id
            Long productId = productVo.getId();
            //查询账目数量（库存数量）
            int accountQuantity = productStockMapper.selectTotalNum(productId, null);
            //盘点数量
            int checkCuantity = stockCheckGoodsDto.getQuantity();
            //盈亏数
            int losses = checkCuantity - accountQuantity;

            //添加盘点单关联商品信息
            stockCheckProduct.setCheckId(stockCheckGoodsDto.getCheckId());
            stockCheckProduct.setProductName(productName);
            stockCheckProduct.setProductId(productVo.getProductId());
            stockCheckProduct.setAccountQuantity(accountQuantity);
            stockCheckProduct.setCheckQuantity(checkCuantity);
            stockCheckProduct.setLosses(losses);
            stockCheckProduct.setRemark(stockCheckGoodsDto.getRemark());
            baseMapper.insert(stockCheckProduct);

            //盘点单关联商品表id
            Long checkProduct = stockCheckProduct.getId();
            //盘点人
            Long stockPerson = uid;
            //盘点数量
            int quantity = stockCheckGoodsDto.getQuantity();

            StockCheckProductPerson stockCheckProductPerson = new StockCheckProductPerson();
            stockCheckProductPerson.setCheckProduct(checkProduct);
            stockCheckProductPerson.setStockPerson(uid);
            stockCheckProductPerson.setQuantity(quantity);
            //新增 盘点单商品关联盘点人表信息
            stockCheckProductPersonMapper.insert(stockCheckProductPerson);
        } else {
            //通过盘点单号和货号查到的有信息就修改
            //盘点数量变动
            int checkCuantity = stockCheckProduct.getCheckQuantity() + stockCheckGoodsDto.getQuantity();
            //盈亏数变动
            int losses = checkCuantity - stockCheckProduct.getAccountQuantity();

            //更新盘点单关联商品信息
            stockCheckProduct.setCheckQuantity(checkCuantity);
            stockCheckProduct.setLosses(losses);
            stockCheckProduct.setRemark(stockCheckGoodsDto.getRemark());
            baseMapper.updateById(stockCheckProduct);

            //盘点单关联商品表id
            Long checkProduct = stockCheckProduct.getId();
            //盘点人
            Long stockPerson = uid;
            StockCheckProductPerson stockCheckProductPerson = stockCheckProductPersonMapper.selectStockCheckProductPerson(stockPerson, checkProduct);

            //关联的盘点人里面没有信息就新增
            if (stockCheckProductPerson == null) {
                //盘点数量   就是当前提交进来的数量
                int quantity = stockCheckGoodsDto.getQuantity();

                stockCheckProductPerson.setCheckProduct(checkProduct);
                stockCheckProductPerson.setStockPerson(uid);
                stockCheckProductPerson.setQuantity(quantity);
                //新增 盘点单商品关联盘点人表信息
                stockCheckProductPersonMapper.insert(stockCheckProductPerson);
            } else {
                //关联的盘点人里面有信息就修改
                //盘点数量   提交进来的数量加上表中原有的数量
                int quantity = stockCheckProductPerson.getQuantity() + stockCheckGoodsDto.getQuantity();

                stockCheckProductPerson.setCheckProduct(checkProduct);
                stockCheckProductPerson.setStockPerson(uid);
                stockCheckProductPerson.setQuantity(quantity);
                //更新 盘点单商品关联盘点人表信息
                stockCheckProductPersonMapper.updateById(stockCheckProductPerson);
            }

        }

    }

    @Override
    public void insertStockCheckProductByDepotId(Long depotId, Long stockCheckId, Long uid) {
        Depot depot=depotService.getById(depotId);
        if(ObjectUtil.isNull(depot)){
            throw  new BusinessException("仓库不存在！");

        }
        List<ProductStockDetails> productStockVoList=Lists.newArrayList();
        if(depot.getDepotCode().equals(GlobalConstant.DepotCode.CP)){
            List<DefectiveProduct> defectiveProductList=defectiveProductService.list();
            for(DefectiveProduct defectiveProduct:defectiveProductList){
                //添加盘点单关联商品信息
                ProductStockDetails details = new ProductStockDetails();
                details.setDepotId(depotId);
                details.setGoodsSn(defectiveProduct.getChgGoodsSn());
                details.setStockSn(defectiveProduct.getStockSn());
                details.setProductImg(defectiveProduct.getProductImg());
                details.setProductName(defectiveProduct.getProductName());
                details.setStockPrice(defectiveProduct.getCostPrice());
                try{
                    ItemVo  itemVo=itemFeign.findProductVoByProductSn(defectiveProduct.getProductSn()).getData();
                    if(ObjectUtil.isNotNull(itemVo)){
                        details.setGoodsId(itemVo.getGoodsId());
                        details.setProductId(itemVo.getProductId());
                        details.setMarkerPrice(itemVo.getMarketPrice());
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
                details.setProductSkuDesp(defectiveProduct.getSpec());
                details.setProductSn(defectiveProduct.getProductSn());
                productStockVoList.add(details);

            }
        }else{
            //库存货品
            productStockVoList = stockDetailsMapper.selectList(new QueryWrapper<ProductStockDetails>().eq("depot_id", depotId));
        }
        //待插入盘点货品
        List<StockCheckProduct> stockCheckProductList = Lists.newArrayList();

        productStockVoList.forEach(productStockVo -> {
            //添加盘点单关联商品信息
            StockCheckProduct stockCheckProduct = new StockCheckProduct();
            stockCheckProduct.setCheckId(stockCheckId);
            stockCheckProduct.setProductName(productStockVo.getProductName());
            stockCheckProduct.setProductId(productStockVo.getProductId());
            stockCheckProduct.setProductSn(productStockVo.getProductSn());
            stockCheckProduct.setStyleNo(productStockVo.getStyleNo());
            stockCheckProduct.setGoodsSn(productStockVo.getGoodsSn());
            stockCheckProduct.setAccountQuantity(1);
            stockCheckProduct.setCheckQuantity(0);
            stockCheckProduct.setLosses(-1);
            stockCheckProduct.setCost(productStockVo.getStockPrice());
            stockCheckProduct.setMarkerPrice(productStockVo.getMarkerPrice());
            stockCheckProduct.setProductSkuDesp(productStockVo.getProductSkuDesp());
            stockCheckProductList.add(stockCheckProduct);
        });
        if (stockCheckProductList.size() > 0) {
            List<List<StockCheckProduct>> lists = ListUtil.fixedGrouping(stockCheckProductList, 100);
            //对数组进行分割，每次提交100条，防止提交过多。
            for (List<StockCheckProduct> stockCheckProducts : lists) {
                saveBatch(stockCheckProducts);
            }
        }
    }

    @Override
    public boolean scanCheckProduct(Long checkId, String productSn, SysAuth sysAuth) {

        StockCheckProduct scp = baseMapper.selectStockCheckProduct(checkId, productSn);
        scp = ObjectUtils.isNotNull(scp) ? new StockCheckProduct() : scp;
        scp.setCheckUserId(sysAuth.getUid());
        scp.setCheckName(sysAuth.getRealName());
        scp.setCheckTime(new Date());
        //通过盘点单号和货号没查到信息就新增
        if (scp == null) {
            ItemVo itemVo = productFeign.findProductVoByProductSn(productSn).getData();
            scp.setProductName(itemVo.getProductName());
            scp.setCheckId(checkId);
            scp.setProductId(itemVo.getProductId());
            scp.setUnit("");
            scp.setAccountQuantity(0);
            scp.setCheckQuantity(1);
            scp.setLosses(1);
            scp.setCost(itemVo.getCostPrice());
            scp.setProductSn(itemVo.getProductSn());
            scp.setMarkerPrice(itemVo.getMarketPrice());
            scp.setStyleNo(itemVo.getStyleNo());
            scp.setGoodsSn(itemVo.getGoodsSn());
            scp.setProductSkuDesp(itemVo.getProductSkuDesp());
            save(scp);

        }
        scp.setCheckUserId(sysAuth.getUid());
        scp.setCheckName(sysAuth.getRealName());
        scp.setCheckTime(new Date());
        scp.setLosses(0);
        scp.setCheckQuantity(1);
        updateById(scp);
        StockCheckProductPerson scpp = new StockCheckProductPerson();
        scpp.setProductId(scp.getProductId());
        scpp.setCheckId(checkId);
        scpp.setCheckProduct(scp.getId());
        scpp.setStockPerson(sysAuth.getUid());
        scpp.setQuantity(1);
        scpp.setStyleNo(scp.getStyleNo());
        scpp.setProductName(scp.getProductName());
        stockCheckProductPersonMapper.insert(scpp);
        return true;
    }

    /**
     * 检查带订单是否盘点过
     *
     * @param checkId
     * @param productSn
     * @return
     */
    @Override
    public Boolean checkProduct(Long checkId, String productSn) {
        StockCheckProduct stockCheckProduct = getOne(new QueryWrapper<StockCheckProduct>().eq("check_id", checkId).eq("product_sn", productSn));
        if (ObjectUtil.isNotNull(stockCheckProduct.getCheckUserId())) {
            return true;
        }
        return false;
    }
}
